package top.yehot.cmmu.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import top.yehot.cmmu.shiro.config.ShiroConstants;
import top.yehot.cmmu.shiro.models.dto.LoginUserDTO;
import top.yehot.cmmu.shiro.session.CustomSession;
import top.yehot.cmmu.shiro.util.ShiroUtil;

/**
 * <p>自定义session过滤器（给自定义session存入登录用户信息），参考【若依】</p>
 * <p> 参考类URL：https://gitee.com/y_project/RuoYi/blob/master/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/web/filter/online/OnlineSessionFilter.java</p>
 * 
 * @author lquan
 * @date 2022-9-10 22:14:19
 */
public class OnlineSessionFilter extends AccessControlFilter {

	private SessionDAO sessionDAO;

	public OnlineSessionFilter(SessionDAO sessionDAO) {
		this.sessionDAO = sessionDAO;
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		if (subject == null || subject.getSession() == null) {
			return true;
		}
		Session session = sessionDAO.readSession(subject.getSession().getId());
		if (session != null && session instanceof CustomSession) {
			CustomSession customSession = (CustomSession) session;
			request.setAttribute(ShiroConstants.ONLINE_SESSION, customSession);
			// 把user对象设置进去
			boolean isGuest = customSession.getUserId() == null || customSession.getUserId() <= 0L;
			if (isGuest == true) {
				LoginUserDTO loginUser = ShiroUtil.getLoginUser();
				if (loginUser != null) {
					customSession.setUserId(loginUser.getUserId());
					customSession.setLoginName(loginUser.getLoginName());
					customSession.setRealName(loginUser.getRealName());
				}
			}
		}
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		if (subject != null) {
			subject.logout();
		}
		saveRequestAndRedirectToLogin(request, response);
		return false;
	}

}
